<template>
  <div class="host-connection-layout">
    <!-- 右上角关闭按钮 -->
    <div class="page-close-btn">
      <el-button @click="goBack" class="close-button">
        <i class="fa fa-times"></i>
      </el-button>
    </div>

    <!-- 左右分栏布局 -->
    <div class="connection-container">
      <!-- 左侧主机目录树 -->
      <div class="left-panel" :style="{ width: leftPanelWidth + 'px' }">
        <div class="panel-header glass-effect">
          <h3><i class="fa fa-sitemap"></i> 主机目录</h3>
          <!-- 搜索框 -->
          <div class="search-container">
            <el-input
              v-model="searchKeyword"
              placeholder="搜索主机名或IP"
              size="small"
              clearable
              @input="handleSearch"
              @clear="handleSearchClear">
              <template #prefix>
                <i class="fa fa-search"></i>
              </template>
            </el-input>
          </div>
        </div>

        <div class="panel-content">
          <div v-if="loading" class="loading-container">
            <i class="el-icon-loading"></i>
            <span>正在加载主机列表...</span>
          </div>

          <div v-else-if="filteredTreeData.length === 0" class="empty-container">
            <i class="fa fa-server"></i>
            <h4>暂无主机</h4>
            <p>请先在主机管理中添加主机</p>
            <el-button type="primary" size="small" @click="goToHostManagement">
              <i class="fa fa-plus"></i> 添加主机
            </el-button>
          </div>

          <!-- 目录树 -->
          <div v-else class="tree-container">
            <el-tree
              ref="treeRef"
              :data="filteredTreeData"
              :props="treeProps"
              :expand-on-click-node="true"
              :default-expand-all="false"
              :default-expanded-keys="expandedKeys"
              node-key="id"
              class="host-tree"
              @node-click="handleNodeClick"
              @node-expand="handleNodeExpand"
              @node-collapse="handleNodeCollapse"
              @node-contextmenu="handleNodeRightClick">
              <template #default="{ node, data }">
                <div
                  class="tree-node"
                  :class="getNodeClass(data)"
                  @dblclick.stop="handleNodeDoubleClick(data)">
                  <i :class="getNodeIcon(data)"></i>
                  <span class="node-label">{{ node.label }}</span>
                  <div v-if="data.type === 'host'" class="node-status">
                    <i :class="data.status === 'online' ? 'fa fa-circle status-online' : 'fa fa-circle status-offline'"></i>
                  </div>
                </div>
              </template>
            </el-tree>
          </div>
        </div>
      </div>

      <!-- 可调节分割线 -->
      <div
        class="resize-handle"
        @mousedown="startResize">
      </div>

      <!-- 右侧终端区域 -->
      <div class="right-panel" :style="{ width: rightPanelWidth + 'px' }">
        <div class="panel-header glass-effect">
          <h3><i class="fa fa-terminal"></i> SSH终端</h3>
          <!-- 标签页控制 - 隐藏连接按钮，只保留关闭所有按钮 -->
          <div class="tab-controls" v-if="terminalTabs.length > 0">
            <el-button size="small" @click="closeAllTabs" class="close-all-btn">
              <i class="fa fa-times"></i> 关闭所有
            </el-button>
          </div>
        </div>

        <div class="panel-content">
          <!-- 默认欢迎界面 -->
          <div v-if="terminalTabs.length === 0" class="welcome-container">
            <div class="welcome-content">
              <i class="fa fa-terminal welcome-icon"></i>
              <h3>SSH终端连接</h3>
              <p>请从左侧选择主机进行连接</p>
              <div class="welcome-tips">
                <div class="tip-item">
                  <i class="fa fa-mouse-pointer"></i>
                  <span>点击主机节点建立连接</span>
                </div>
                <div class="tip-item">
                  <i class="fa fa-hand-pointer-o"></i>
                  <span>右键主机节点查看更多选项</span>
                </div>
                <div class="tip-item">
                  <i class="fa fa-search"></i>
                  <span>使用搜索框快速定位主机</span>
                </div>
              </div>
            </div>
          </div>

          <!-- 终端标签页 -->
          <div v-else class="terminal-tabs-container">
            <el-tabs
              v-model="activeTab"
              type="card"
              closable
              @tab-remove="closeTab"
              @tab-click="switchTab"
              class="terminal-tabs">
              <el-tab-pane
                v-for="tab in terminalTabs"
                :key="tab.id"
                :label="tab.label"
                :name="tab.id">
                <template #label>
                  <div class="tab-label">
                    <i :class="[
                      'fa fa-circle',
                      tab.status === 'connected' ? 'tab-status-connected' :
                      tab.status === 'connecting' ? 'tab-status-connecting' :
                      'tab-status-offline'
                    ]"></i>
                    <span>{{ tab.label }}</span>
                  </div>
                </template>

                <!-- SSH终端组件 -->
                <div class="terminal-wrapper">
                  <NewSSHTerminal
                    v-if="tab.hostInfo"
                    :hostInfo="tab.hostInfo"
                    :connection-id="tab.id"
                    :access-token="tab.accessToken"
                    :hide-connect-button="true"
                    @connection-status="updateTabStatus"
                    @token-updated="updateTabToken"
                    :key="tab.id" />
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </div>
    </div>

    <!-- 右键菜单 -->
    <el-dropdown
      ref="contextMenuRef"
      trigger="manual"
      :style="contextMenuStyle"
      class="context-menu">
      <span></span>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="connectHost" :disabled="!selectedHost || selectedHost.status !== 'online'">
            <i class="fa fa-terminal"></i> 连接主机
          </el-dropdown-item>
          <el-dropdown-item @click="viewHostDetails" :disabled="!selectedHost">
            <i class="fa fa-info-circle"></i> 查看详情
          </el-dropdown-item>
          <el-dropdown-item @click="refreshHostStatus" :disabled="!selectedHost">
            <i class="fa fa-refresh"></i> 刷新状态
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>
<script setup lang="ts">
import NewSSHTerminal from '@/components/NewSSHTerminal.vue'
import axios from 'axios'
import { ElMessage } from 'element-plus'
import { computed, nextTick, onMounted, onUnmounted, ref } from 'vue'
import { useRouter } from 'vue-router'

const router = useRouter()

// 页面访问标记 - 用于区分刷新和路由跳转
const isPageRefresh = ref(false)

// 响应式数据
const hosts = ref([])
const hostGroups = ref([])
const loading = ref(true)
const searchKeyword = ref('')

// 状态持久化
const expandedKeys = ref([])
const treeRef = ref()

// 面板大小控制
const leftPanelWidth = ref(350)
const rightPanelWidth = ref(window.innerWidth - 350 - 4)
const isResizing = ref(false)

// 终端标签页
const terminalTabs = ref([])
const activeTab = ref('')
const tabCounter = ref(0)

// 右键菜单
const contextMenuRef = ref()
const selectedHost = ref(null)
const contextMenuStyle = ref({ display: 'none' })

// 树形结构配置
const treeProps = {
  children: 'children',
  label: 'label'
}

// 检测是否为页面刷新
const checkIfPageRefresh = () => {
  // 检查是否有刷新标记
  const isRefreshFlag = sessionStorage.getItem('connection-page-is-refresh')

  if (isRefreshFlag === 'true') {
    // 是页面刷新，保持状态
    isPageRefresh.value = true
    console.log('检测到页面刷新，保持状态')
    // 清除刷新标记
    sessionStorage.removeItem('connection-page-is-refresh')
  } else {
    // 不是页面刷新，清除状态
    isPageRefresh.value = false
    clearStoredState()
    console.log('检测到路由跳转，清除状态')
  }
}

// 清除存储的状态
const clearStoredState = () => {
  localStorage.removeItem('connection-expanded-keys')
  localStorage.removeItem('connection-terminal-tabs')
  localStorage.removeItem('connection-active-tab')

  // 重置组件状态
  expandedKeys.value = []
  terminalTabs.value = []
  activeTab.value = ''
}

// 页面刷新检测
const handleBeforeUnload = () => {
  // 设置刷新标记
  sessionStorage.setItem('connection-page-is-refresh', 'true')
}

// 组件挂载
onMounted(async () => {
  checkIfPageRefresh()
  await fetchData()
  loadPanelSizes()

  // 只有在页面刷新时才加载保存的状态
  if (isPageRefresh.value) {
    loadExpandedKeys()
    await loadTerminalTabs()
  }

  document.addEventListener('mousemove', handleMouseMove)
  document.addEventListener('mouseup', stopResize)
  document.addEventListener('click', hideContextMenu)
  window.addEventListener('resize', handleWindowResize)
  window.addEventListener('beforeunload', handleBeforeUnload)
})

// 组件销毁时清理事件监听器
onUnmounted(() => {
  document.removeEventListener('mousemove', handleMouseMove)
  document.removeEventListener('mouseup', stopResize)
  document.removeEventListener('click', hideContextMenu)
  window.removeEventListener('resize', handleWindowResize)
  window.removeEventListener('beforeunload', handleBeforeUnload)

  // 如果是路由跳转（不是页面刷新），清除刷新标记
  if (!isPageRefresh.value) {
    sessionStorage.removeItem('connection-page-is-refresh')
  }
})

// 获取数据
const fetchData = async () => {
  try {
    loading.value = true
    const [hostsResponse, groupsResponse] = await Promise.all([
      axios.get('/api/hosts/'),
      axios.get('/api/hostgroups/')
    ])

    hosts.value = hostsResponse.data.results || hostsResponse.data || []
    hostGroups.value = groupsResponse.data.results || groupsResponse.data || []

    console.log('获取到的主机数据:', hosts.value)
    console.log('获取到的主机组数据:', hostGroups.value)

    // 查看第一个主机的字段结构
    if (hosts.value.length > 0) {
      console.log('第一个主机的字段:', Object.keys(hosts.value[0]))
      console.log('第一个主机的完整数据:', hosts.value[0])
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

// 构建树形数据
const treeData = computed(() => {
  console.log('开始构建树形数据，主机总数:', hosts.value.length, '主机组数:', hostGroups.value.length)

  if (hostGroups.value.length === 0) {
    return []
  }

  // 环境名称映射
  const envNames = {
    'dev': '开发环境',
    'test': '测试环境',
    'staging': '预发布环境',
    'prod': '生产环境'
  }

  // 1. 先获取所有存在的环境
  const existingEnvironments = [...new Set(hostGroups.value.map(group => group.environment))].filter(Boolean)
  console.log('存在的环境:', existingEnvironments)

  // 调试：显示所有主机的关联字段
  console.log('所有主机的关联字段调试:')
  hosts.value.forEach((host, index) => {
    if (index < 3) { // 只显示前3个主机
      console.log(`主机 ${host.hostname}:`, {
        id: host.id,
        host_groups: host.host_groups,
        host_group_names: host.host_group_names,
        所有字段: Object.keys(host)
      })
    }
  })

  const treeResult = existingEnvironments.map(envKey => {
    // 2. 获取该环境下的所有主机组
    const envGroups = hostGroups.value.filter(group => group.environment === envKey)
    console.log(`环境 ${envKey} 下的主机组:`, envGroups)

    const children = envGroups.map(group => {
      // 3. 获取该主机组下的所有主机
      console.log(`正在查找主机组 ${group.name} (ID: ${group.id}) 下的主机`)

      // 使用host_groups字段匹配（多对多关系）
      const groupHosts = hosts.value.filter(host => {
        // host_groups可能是数组，包含主机组ID
        const hostGroups = host.host_groups || []
        const matches = hostGroups.includes(group.id)

        if (matches) {
          console.log(`找到匹配主机:`, host.hostname, '所属主机组:', host.host_groups, '主机组名称:', host.host_group_names)
        }
        return matches
      })

      console.log(`主机组 ${group.name} 下的主机数量:`, groupHosts.length)

      return {
        id: `group-${group.id}`,
        label: group.name,
        type: 'group',
        environment: envKey,
        children: groupHosts.map(host => ({
          id: `host-${host.id}`,
          label: `${host.hostname} (${host.public_ip || host.ip})`,
          type: 'host',
          status: host.status || 'offline',
          hostData: host
        }))
      }
    })

    return {
      id: envKey,
      label: envNames[envKey] || envKey,
      type: 'environment',
      environment: envKey,
      children: children
    }
  })

  console.log('构建的树形数据:', treeResult)
  return treeResult
})

// 过滤后的树形数据
const filteredTreeData = computed(() => {
  if (!searchKeyword.value) return treeData.value

  const keyword = searchKeyword.value.toLowerCase()
  const matchedPaths = new Set()

  const filterTree = (nodes, parentPath = []) => {
    return nodes.map(node => {
      const currentPath = [...parentPath, node.id]

      if (node.type === 'host') {
        const host = node.hostData
        const matches = host.hostname.toLowerCase().includes(keyword) ||
                       host.public_ip.toLowerCase().includes(keyword) ||
                       (host.private_ip && host.private_ip.toLowerCase().includes(keyword))

        if (matches) {
          // 记录匹配主机的完整路径，包括所有父节点
          currentPath.forEach(pathId => matchedPaths.add(pathId))
        }
        return matches ? node : null
      } else {
        const filteredChildren = filterTree(node.children || [], currentPath).filter(Boolean)
        if (filteredChildren.length > 0) {
          // 如果有匹配的子节点，记录当前节点需要展开
          matchedPaths.add(node.id)
          return { ...node, children: filteredChildren }
        }
        return null
      }
    }).filter(Boolean)
  }

  const result = filterTree(treeData.value)

  // 自动展开匹配的路径
  if (matchedPaths.size > 0) {
    autoExpandMatchedPaths(Array.from(matchedPaths))
  }

  return result
})

// 自动展开匹配的路径
const autoExpandMatchedPaths = (matchedNodeIds) => {
  // 延迟执行，确保DOM已更新
  nextTick(() => {
    matchedNodeIds.forEach(nodeId => {
      if (!expandedKeys.value.includes(nodeId)) {
        expandedKeys.value.push(nodeId)
      }
    })
    saveExpandedKeys()

    // 通知树组件更新展开状态
    if (treeRef.value) {
      treeRef.value.setExpandedKeys(expandedKeys.value)
    }
  })
}

// 事件处理方法
const handleSearch = () => {
  // 搜索逻辑已在computed中处理
}

const handleSearchClear = () => {
  // 清空搜索时，恢复之前保存的展开状态
  nextTick(() => {
    if (treeRef.value) {
      treeRef.value.setExpandedKeys(expandedKeys.value)
    }
  })
}

const handleNodeClick = (data, node, component) => {
  if (data.type === 'host') {
    // 主机节点：选中主机，不展开/折叠
    selectedHost.value = data.hostData
  } else {
    // 环境或主机组节点：展开/折叠（Element Tree会自动处理）
    // 这里不需要额外处理，expand-on-click-node="true"会自动处理
  }
}

const handleNodeDoubleClick = (data) => {
  console.log('双击节点:', data)
  // 双击直接连接主机
  if (data.type === 'host') {
    console.log('双击主机，直接连接:', data.hostData)
    // 直接调用连接函数
    connectHost(data.hostData)
  }
}

const handleNodeExpand = (data, node) => {
  if (!expandedKeys.value.includes(data.id)) {
    expandedKeys.value.push(data.id)
    saveExpandedKeys()
  }
}

const handleNodeCollapse = (data, node) => {
  const index = expandedKeys.value.indexOf(data.id)
  if (index > -1) {
    expandedKeys.value.splice(index, 1)
    saveExpandedKeys()
  }
}

const handleNodeRightClick = (event, data) => {
  if (data.type === 'host') {
    event.preventDefault()
    selectedHost.value = data.hostData
    showContextMenu(event)
  }
}

const showContextMenu = (event) => {
  contextMenuStyle.value = {
    display: 'block',
    position: 'fixed',
    left: event.clientX + 'px',
    top: event.clientY + 'px',
    zIndex: 9999
  }
  nextTick(() => {
    contextMenuRef.value?.handleOpen()
  })
}

const hideContextMenu = () => {
  contextMenuStyle.value.display = 'none'
  contextMenuRef.value?.handleClose()
}

// 连接主机
const connectHost = async (host = selectedHost.value) => {
  if (!host) {
    ElMessage.warning('请选择要连接的主机')
    return
  }

  console.log('开始连接主机:', host.hostname)

  try {
    // 允许同一个主机开多个连接，不再检查重复连接

    // 请求SSH访问令牌
    const response = await axios.post('/api/ssh/request-access/', {
      host_id: host.id
    })

    if (response.data.success) {
      // 创建新的终端标签页
      const tabId = `tab-${++tabCounter.value}`

      // 检查是否已有同名主机的标签页，如果有则添加序号
      const existingTabs = terminalTabs.value.filter(tab => tab.hostInfo.id === host.id)
      const tabLabel = existingTabs.length > 0 ? `${host.hostname} (${existingTabs.length + 1})` : host.hostname

      const newTab = {
        id: tabId,
        label: tabLabel,
        hostInfo: host,
        status: 'connecting',
        accessToken: response.data.access_token
      }

      terminalTabs.value.push(newTab)
      activeTab.value = tabId
      saveTerminalTabs()

      // 显示连接状态提示
      ElMessage({
        message: `正在连接到 ${host.hostname}...`,
        type: 'info',
        duration: 2000,
        showClose: false
      })
    } else {
      ElMessage.error(response.data.message || '无权访问此主机')
    }
  } catch (error) {
    console.error('连接主机失败:', error)
    ElMessage.error('连接主机失败，请检查权限')
  }

  hideContextMenu()
}

// 标签页管理
const closeTab = (tabId) => {
  const index = terminalTabs.value.findIndex(tab => tab.id === tabId)
  if (index > -1) {
    terminalTabs.value.splice(index, 1)

    // 如果关闭的是当前活动标签页，切换到其他标签页
    if (activeTab.value === tabId) {
      if (terminalTabs.value.length > 0) {
        activeTab.value = terminalTabs.value[Math.max(0, index - 1)].id
      } else {
        activeTab.value = ''
      }
    }
    saveTerminalTabs()
  }
}

const closeAllTabs = () => {
  terminalTabs.value = []
  activeTab.value = ''
  saveTerminalTabs()
}

const switchTab = (tab) => {
  activeTab.value = tab.name
  saveTerminalTabs()
}

const updateTabStatus = (connectionId, status) => {
  const tab = terminalTabs.value.find(t => t.id === connectionId)
  if (tab) {
    tab.status = status

    // 连接成功时显示提示
    if (status === 'connected') {
      ElMessage({
        message: `已成功连接到 ${tab.hostInfo.hostname}`,
        type: 'success',
        duration: 2000,
        showClose: false
      })
    }

    // 保存状态变化
    saveTerminalTabs()
  }
}

// 重新连接指定标签页的主机
const reconnectTab = async (tabId) => {
  const tab = terminalTabs.value.find(t => t.id === tabId)
  if (!tab) return

  try {
    tab.status = 'connecting'

    // 重新获取访问令牌
    const response = await axios.post('/api/ssh/request-access/', {
      host_id: tab.hostInfo.id
    })

    if (response.data.success) {
      tab.accessToken = response.data.access_token
      ElMessage({
        message: `正在重新连接到 ${tab.hostInfo.hostname}...`,
        type: 'info',
        duration: 2000,
        showClose: false
      })
    } else {
      tab.status = 'disconnected'
      ElMessage.error(response.data.message || '无权访问此主机')
    }
  } catch (error) {
    console.error('重新连接失败:', error)
    tab.status = 'disconnected'
    ElMessage.error('重新连接失败，请检查权限')
  }

  saveTerminalTabs()
}

// 更新标签页的访问令牌
const updateTabToken = (connectionId, accessToken) => {
  const tab = terminalTabs.value.find(t => t.id === connectionId)
  if (tab) {
    tab.accessToken = accessToken
    saveTerminalTabs()
  }
}

// 面板大小调整
const startResize = (event) => {
  isResizing.value = true
  event.preventDefault()
}

const handleMouseMove = (event) => {
  if (!isResizing.value) return

  const containerWidth = window.innerWidth
  const newLeftWidth = Math.max(250, Math.min(600, event.clientX))
  const newRightWidth = containerWidth - newLeftWidth - 4 // 减去分割线宽度

  leftPanelWidth.value = newLeftWidth
  rightPanelWidth.value = newRightWidth
}

const stopResize = () => {
  if (isResizing.value) {
    isResizing.value = false
    savePanelSizes()
  }
}

const loadPanelSizes = () => {
  const saved = localStorage.getItem('connection-panel-sizes')
  if (saved) {
    const sizes = JSON.parse(saved)
    leftPanelWidth.value = sizes.left || 350
    rightPanelWidth.value = sizes.right || (window.innerWidth - 350 - 4)
  } else {
    // 初始化时计算右侧面板宽度
    rightPanelWidth.value = window.innerWidth - leftPanelWidth.value - 4
  }
}

const savePanelSizes = () => {
  localStorage.setItem('connection-panel-sizes', JSON.stringify({
    left: leftPanelWidth.value,
    right: rightPanelWidth.value
  }))
}

const handleWindowResize = () => {
  // 窗口大小变化时，保持左侧面板宽度不变，调整右侧面板宽度
  rightPanelWidth.value = window.innerWidth - leftPanelWidth.value - 4
}

// 状态持久化函数
const saveExpandedKeys = () => {
  localStorage.setItem('connection-expanded-keys', JSON.stringify(expandedKeys.value))
}

const loadExpandedKeys = () => {
  const saved = localStorage.getItem('connection-expanded-keys')
  if (saved) {
    expandedKeys.value = JSON.parse(saved)
  }
}

const saveTerminalTabs = () => {
  const tabsData = terminalTabs.value.map(tab => ({
    id: tab.id,
    label: tab.label,
    hostInfo: tab.hostInfo,
    status: 'disconnected', // 刷新后重置为断开状态
    accessToken: null // 访问令牌不保存，需要重新获取
  }))
  localStorage.setItem('connection-terminal-tabs', JSON.stringify(tabsData))
  localStorage.setItem('connection-active-tab', activeTab.value)
}

const loadTerminalTabs = async () => {
  const saved = localStorage.getItem('connection-terminal-tabs')
  const savedActiveTab = localStorage.getItem('connection-active-tab')

  if (saved) {
    const tabsData = JSON.parse(saved)

    // 为每个标签页重新获取访问令牌
    for (const tab of tabsData) {
      try {
        const response = await axios.post('/api/ssh/request-access/', {
          host_id: tab.hostInfo.id
        })

        if (response.data.success) {
          tab.accessToken = response.data.access_token
          tab.status = 'connecting'
        } else {
          tab.status = 'disconnected'
          tab.accessToken = null
        }
      } catch (error) {
        console.error(`获取主机 ${tab.hostInfo.hostname} 访问令牌失败:`, error)
        tab.status = 'disconnected'
        tab.accessToken = null
      }
    }

    terminalTabs.value = tabsData
    if (savedActiveTab && tabsData.find(tab => tab.id === savedActiveTab)) {
      activeTab.value = savedActiveTab
    }
    // 更新计数器
    if (tabsData.length > 0) {
      const maxId = Math.max(...tabsData.map(tab => parseInt(tab.id.replace('tab-', ''))))
      tabCounter.value = maxId
    }
  }
}

// 其他方法
const viewHostDetails = () => {
  if (selectedHost.value) {
    router.push(`/cmdb/hosts?id=${selectedHost.value.id}`)
  }
  hideContextMenu()
}

const refreshHostStatus = async () => {
  if (selectedHost.value) {
    try {
      await axios.post(`/api/hosts/${selectedHost.value.id}/check-status/`)
      await fetchData()
      ElMessage.success('主机状态已刷新')
    } catch (error) {
      ElMessage.error('刷新主机状态失败')
    }
  }
  hideContextMenu()
}

const goToHostManagement = () => {
  router.push('/cmdb/hosts')
}

const goBack = () => {
  router.push('/')
}

// 树节点样式
const getNodeClass = (data) => {
  const classes = [`node-${data.type}`]
  if (data.type === 'host') {
    classes.push(`status-${data.status}`)
  }
  return classes
}

const getNodeIcon = (data) => {
  const iconMap = {
    'environment': 'fa fa-globe',
    'group': 'fa fa-folder',
    'host': 'fa fa-server'
  }
  return iconMap[data.type] || 'fa fa-circle'
}
</script>

<style lang="scss" scoped>
.host-connection-layout {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  width: 100vw;
  height: 100vh;
  background: transparent;
  overflow: hidden;
  z-index: 9999;
}

/* 右上角关闭按钮 */
.page-close-btn {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 10000;
}

.close-button {
  background: rgba(255, 255, 255, 0.05) !important;
  border: 1px solid rgba(255, 255, 255, 0.15) !important;
  color: rgba(255, 255, 255, 0.8) !important;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1) !important;
  border-radius: 50% !important;
  width: 40px !important;
  height: 40px !important;
  padding: 0 !important;
  display: flex !important;
  align-items: center !important;
  justify-content: center !important;
  backdrop-filter: blur(20px) !important;
  box-shadow:
    inset 0 1px 0 rgba(255, 255, 255, 0.1),
    0 4px 15px rgba(0, 0, 0, 0.1) !important;
  position: relative !important;
  overflow: hidden !important;
}

.close-button::before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: linear-gradient(135deg,
    rgba(255, 182, 193, 0.1) 0%,
    rgba(255, 160, 160, 0.15) 50%,
    rgba(255, 105, 105, 0.1) 100%);
  border-radius: 50%;
  opacity: 0;
  transition: opacity 0.3s ease;
  z-index: -1;
}

.close-button:hover {
  background: rgba(255, 255, 255, 0.08) !important;
  border-color: rgba(255, 182, 193, 0.4) !important;
  color: rgba(255, 182, 193, 0.9) !important;
  transform: scale(1.05) !important;
  box-shadow:
    inset 0 1px 0 rgba(255, 255, 255, 0.15),
    0 6px 20px rgba(0, 0, 0, 0.15),
    0 0 15px rgba(255, 182, 193, 0.2) !important;
}

.close-button:hover::before {
  opacity: 1;
}

.close-button:active {
  transform: scale(0.98) !important;
  transition: transform 0.1s ease !important;
}

.close-button i {
  font-size: 16px !important;
  position: relative !important;
  z-index: 1 !important;
  transition: color 0.3s ease !important;
}

.connection-container {
  display: flex;
  height: 100vh;
  width: 100vw;
}

/* 左侧面板 */
.left-panel {
  display: flex;
  flex-direction: column;
  border-right: 1px solid rgba(164, 244, 186, 0.2);
  background: rgba(255, 255, 255, 0.05);
  backdrop-filter: blur(20px);
}

.panel-header {
  padding: 12px 20px;
  border-bottom: 1px solid rgba(164, 244, 186, 0.2);

  h3 {
    color: #00eaff;
    margin: 0 0 15px 0;
    font-size: 1.2em;
    text-shadow: 0 0 10px rgba(0, 234, 255, 0.3);

    i {
      margin-right: 8px;
    }
  }
}

.search-container {
  .el-input {
    :deep(.el-input__wrapper) {
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(164, 244, 186, 0.3);
      border-radius: 8px;
      backdrop-filter: blur(10px);
    }

    :deep(.el-input__inner) {
      color: #ffffff;
      background: transparent;

      &::placeholder {
        color: rgba(255, 255, 255, 0.5);
      }
    }

    :deep(.el-input__prefix) {
      color: rgba(164, 244, 186, 0.7);
    }
  }
}

.panel-content {
  flex: 1;
  overflow: auto;
  padding: 10px;
}

/* 目录树样式 */
.tree-container {
  height: 100%;
}

.host-tree {
  background: transparent;
  color: #ffffff;

  :deep(.el-tree-node__content) {
    background: transparent;
    border-radius: 6px;
    margin: 2px 0;
    padding: 8px 12px;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(164, 244, 186, 0.1);
    }
  }

  :deep(.el-tree-node__expand-icon) {
    color: rgba(164, 244, 186, 0.7);
  }

  :deep(.el-tree-node__label) {
    color: #ffffff;
  }
}

.tree-node {
  display: flex;
  align-items: center;
  width: 100%;

  i {
    margin-right: 8px;
    width: 16px;
  }

  .node-label {
    flex: 1;
    font-size: 0.9em;
  }

  .node-status {
    margin-left: auto;

    .status-online {
      color: #2ed573;
      font-size: 8px;
      animation: pulse 2s infinite;
    }

    .status-offline {
      color: #ff4757;
      font-size: 8px;
    }
  }
}

.node-environment {
  i {
    color: #00eaff;
  }

  .node-label {
    color: #00eaff;
    font-weight: 600;
  }
}

.node-group {
  i {
    color: rgba(164, 244, 186, 0.8);
  }

  .node-label {
    color: rgba(255, 255, 255, 0.9);
  }
}

.node-host {
  i {
    color: rgba(255, 255, 255, 0.7);
  }

  .node-label {
    color: rgba(255, 255, 255, 0.8);
    font-size: 0.85em;
  }

  &.status-online {
    .node-label {
      color: #ffffff;
    }
  }

  &.status-offline {
    opacity: 0.6;
  }
}

/* 分割线 */
.resize-handle {
  width: 4px;
  background: rgba(164, 244, 186, 0.2);
  cursor: col-resize;
  transition: background 0.3s ease;

  &:hover {
    background: rgba(164, 244, 186, 0.4);
  }
}

/* 右侧面板 */
.right-panel {
  display: flex;
  flex-direction: column;
  background: rgba(255, 255, 255, 0.03);
  backdrop-filter: blur(20px);
}

/* 欢迎界面 */
.welcome-container {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 40px;
}

.welcome-content {
  text-align: center;
  color: rgba(255, 255, 255, 0.8);

  .welcome-icon {
    font-size: 4em;
    color: #00eaff;
    margin-bottom: 20px;
    text-shadow: 0 0 20px rgba(0, 234, 255, 0.5);
  }

  h3 {
    color: #ffffff;
    margin: 20px 0;
    font-size: 1.5em;
  }

  p {
    margin-bottom: 30px;
    font-size: 1.1em;
    color: rgba(255, 255, 255, 0.6);
  }
}

.welcome-tips {
  display: flex;
  flex-direction: column;
  gap: 15px;
  margin-top: 30px;
}

.tip-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px 20px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 8px;
  border: 1px solid rgba(164, 244, 186, 0.2);

  i {
    color: rgba(164, 244, 186, 0.7);
    width: 20px;
  }

  span {
    color: rgba(255, 255, 255, 0.8);
  }
}

/* 终端标签页 */
.terminal-tabs-container {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.terminal-tabs {
  height: 100%;

  :deep(.el-tabs__header) {
    background: transparent;
    border-bottom: none;
    margin: 0;
    padding: 8px 0;
  }

  :deep(.el-tabs__nav-wrap) {
    padding: 8px 15px;
  }

  :deep(.el-tabs__nav) {
    border: none;
  }

  :deep(.el-tabs__active-bar) {
    display: none;
  }

  :deep(.el-tabs__item) {
    background: rgba(164, 244, 186, 0.05);
    border: 1px solid rgba(164, 244, 186, 0.2);
    border-radius: 20px;
    margin-right: 12px;
    color: rgba(255, 255, 255, 0.8);
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    padding: 8px 16px;
    position: relative;
    backdrop-filter: blur(10px);
    min-width: auto;
    white-space: nowrap;

    &.is-active {
      background: rgba(164, 244, 186, 0.15);
      color: #ffffff;
      border-color: rgba(164, 244, 186, 0.5);
      box-shadow: 0 2px 8px rgba(164, 244, 186, 0.2);
      transform: none;
    }

    &:hover {
      background: rgba(164, 244, 186, 0.1);
      color: #ffffff;
      border-color: rgba(164, 244, 186, 0.4);
      transform: none;
    }
  }

  :deep(.el-tabs__content) {
    flex: 1;
    height: calc(100vh - 100px);
    padding: 0;
    overflow: hidden;
  }

  :deep(.el-tab-pane) {
    height: 100%;
    overflow: hidden;
  }
}

.tab-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 13px;
  font-weight: 500;

  .tab-status-online {
    color: #2ed573;
    font-size: 8px;
    animation: pulse 2s infinite;
  }

  .tab-status-offline {
    color: #ff4757;
    font-size: 8px;
  }

  .tab-status-connected {
    color: #2ed573;
    font-size: 10px;
  }

  .tab-status-connecting {
    color: #ff9500;
    font-size: 10px;
    animation: pulse 1.5s infinite;
  }
}

.terminal-wrapper {
  height: calc(100vh - 100px);
  background: #000000;
  border-radius: 0 0 8px 8px;
  overflow: hidden;
  position: relative;
}

.tab-controls {
  display: flex;
  gap: 10px;

  .close-all-btn {
    background: rgba(255, 87, 87, 0.1) !important;
    border: 1px solid rgba(255, 87, 87, 0.3) !important;
    color: rgba(255, 255, 255, 0.8) !important;
    font-size: 12px !important;
    padding: 6px 12px !important;
    border-radius: 6px !important;
    transition: all 0.3s ease !important;

    &:hover {
      background: rgba(255, 87, 87, 0.2) !important;
      border-color: rgba(255, 87, 87, 0.5) !important;
      color: #ffffff !important;
      transform: translateY(-1px) !important;
    }

    i {
      margin-right: 4px;
    }
  }
}

/* 加载和空状态 */
.loading-container,
.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 200px;
  color: rgba(255, 255, 255, 0.8);
}

.loading-container i {
  font-size: 2em;
  color: #00eaff;
  margin-bottom: 15px;
  animation: rotate 2s linear infinite;
}

.empty-container i {
  font-size: 3em;
  color: rgba(255, 255, 255, 0.3);
  margin-bottom: 15px;
}

.empty-container h4 {
  margin: 15px 0 10px 0;
  color: rgba(255, 255, 255, 0.9);
}

.empty-container p {
  margin-bottom: 20px;
  color: rgba(255, 255, 255, 0.6);
  font-size: 0.9em;
}

/* 右键菜单 */
.context-menu {
  :deep(.el-dropdown-menu) {
    background: rgba(164, 244, 186, 0.15);
    border: 1px solid rgba(164, 244, 186, 0.3);
    border-radius: 8px;
    backdrop-filter: blur(20px);
    box-shadow: 0 8px 32px rgba(0, 0, 0, 0.3);
  }

  :deep(.el-dropdown-menu__item) {
    background: transparent;
    color: #ffffff;
    padding: 8px 16px;
    transition: all 0.3s ease;

    &:hover {
      background: rgba(164, 244, 186, 0.1);
      color: #ffffff;
    }

    &.is-disabled {
      color: rgba(255, 255, 255, 0.3);
    }

    i {
      margin-right: 8px;
      color: rgba(164, 244, 186, 0.7);
    }
  }
}

/* 动画 */
@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

@keyframes pulse {
  0%, 100% {
    opacity: 1;
  }
  50% {
    opacity: 0.5;
  }
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .left-panel {
    min-width: 300px;
  }

  .right-panel {
    min-width: 500px;
  }
}

@media (max-width: 768px) {
  .connection-container {
    flex-direction: column;
  }

  .left-panel,
  .right-panel {
    width: 100% !important;
    height: 50%;
  }

  .resize-handle {
    display: none;
  }
}
</style>
